<template>
  <div>
    <div style="
        margin-bottom: 20px;
        margin: 0 auto;
        margin: 10px;
        padding: 10px;
        background-color: #fff;
        box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
      ">
      <div>
        <el-input style="width: 260px; margin-right: 10px" v-model="data.name" placeholder="请输入商品名字查询"
          :prefix-icon="Search" />
        <el-button type="primary" style="margin-left: 10px" @click="load">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
        <el-button type="primary" @click="handleAdd" style="background-color: #409eff">新增</el-button>
      </div>
    </div>

    <div class="card" style="margin: 10px; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px">
      <div>
        <el-table :data="data.tableData" style="width: 100%">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="productName" label="商品名称" />
          <!-- <el-table-column align="center" prop="password" label="密码" /> -->
          <el-table-column align="center" #default="scope" prop="image" label="商品图片">
            <img :src="scope.row.image" alt="" srcset="" width="100" height="100" />
          </el-table-column>
          <el-table-column align="center" prop="des" label="描述" class="description" />
          <el-table-column align="center" prop="price" label="价格" />
          <el-table-column align="center" prop="inventory" label="库存" />
          <el-table-column align="center" prop="type" label="类型" />
          <el-table-column align="center" #default="scope" prop="inventory" label="状态">
            <span v-if="scope.row.valid == 1">上架</span>
            <span v-else>下架</span>
          </el-table-column>
          <el-table-column #default="scope" width="250">
            <el-button type="warning" plain v-if="scope.row.valid == 1" @click="UpAndDown(scope.row)">下架</el-button>
            <el-button type="warning" plain v-else @click="UpAndDown(scope.row)">上架</el-button>
            <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @click="del(scope.row.productId)">删除</el-button>
          </el-table-column>
        </el-table>

        <div style="
            background-color: #fff;
            display: flex;
            justify-content: flex-end;
            padding: 10px;
          ">
          <el-pagination style="padding: 10px; text-align: right; margin-right: 10px" v-model:current-page="data.page"
            v-model:page-size="data.pageSize" @current-change="handleCurrentChange" background layout="prev,pager,next"
            :total="data.total"></el-pagination>
        </div>
      </div>
    </div>

    <el-dialog width="30%" v-model="data.FormVisible" title="商品信息" style="text-align: center">
      <el-form :model="data.form" label-width="100px" label-position="right" style="padding-right: 40px">
        <el-upload class="avatar-uploader" :on-success="handleAvatarSuccess" :show-file-list="false" style="text-align:center; margin: 0 auto;margin-bottom: 18px;padding-left: 40px"
          action="http://localhost:8081/product/upload">
          <img v-if="data.form.image" :src="data.form.image" class="avatar" style="width: 200px; height: 200px" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <el-form-item label="商品名称">
          <el-input v-model="data.form.productName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="data.form.des" type="textarea" autocomplete="off" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="data.form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="data.form.inventory" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="data.form.type" placeholder="商品类型">
            <el-option label="美食" value="美食" />
            <el-option label="居家" value="居家" />
            <el-option label="电器" value="电器" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.FormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save"> 确 认 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.centerDialogVisible" width="500" title="提示">
      <span>是否确定删除商品</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="delUser"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive,ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/http";
// var imageUrl = ref('')
const data = reactive({
  productName: "",
  des: "",
  inventory: "",
  productId: "",
  createTime: "",
  updateTime: "",
  price: "",
  image: "",
  valid: "",
  type: "",
  tableData: [],
  total: 0,
  pageSize: 5, //每页的个数
  page: 1, //当前的页码
  FormVisible: false,
  centerDialogVisible: false,
  form: {},

  //上传后的文件列表
  fileList: [],
  //请求头
  headers: { "Content-Type": "multipart/form-data" },
});

const  handleAvatarSuccess = (res, file) => {
  // console.log(res.data);
  // console.log(file);
  var index = res.data.indexOf("//");
      if (index !== -1) {
        var result = res.data.substring(index);
        console.log(result);
        data.form.image = "https:" + result;
      }
}


const changeFile = (file) => {
  const formData = new FormData();
  formData.append('file', file);
  console.log(file);

  request
    .request({
      url: "/productAPI/product/upload",
      method: "POST",
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data', // 设置 Content-Type 为 multipart/form-data
      }
    })
    .then((res) => {
      var index = res.data.indexOf("//");
      if (index !== -1) {
        var result = res.data.substring(index);
        image = "https:" + result;
        return true;
      }
    });
}

const load = () => {
  request
    .get("/productAPI/product/page", {
      params: {
        page: data.page,
        pageSize: data.pageSize,
        productName: data.name,
      },
    })
    .then((res) => {
      data.tableData = res.data?.records || [];
      data.total = res.data?.total || 0;
    });
};
//调用方法获取后端数据
load();

const UpAndDown = (row) => {
  if (row.valid == 1) {
    row.valid = 0;
  } else if (row.valid == 0) {
    row.valid = 1;
  }
  request
    .get("/productAPI/product/up", {
      params: {
        productId: row.productId,
        valid: row.valid,
      },
    })
    .then((res) => {
      load();
    });
}

const handleCurrentChange = (pageNum) => {
  //当翻页的时候 重新加载数据即可
  load();
};

//重置数据
const reset = () => {
  data.name = "";
  load();
};

//点击打开新增表单，并重置数据
const handleAdd = () => {
  data.form = {};
  data.FormVisible = true;
};

//发送新增请求
const save = () => {
  console.log(data.form);
  request
    .request({
      url: data.form.productId ? "/productAPI/product" : "/productAPI/product",
      method: data.form.productId ? "PUT" : "POST",
      data: {
        productId: data.form.productId,
        productName: data.form.productName,
        des: data.form.des,
        inventory: data.form.inventory,
        price: data.form.price,
        image: data.form.image,
        type: data.form.type,
        valid: 1
      },
    })
    .then((res) => {
      if (res.code === 1) {
        load(); //重新加载数据
        data.FormVisible = false; //关闭弹窗
        ElMessage.success("操作成功");
      } else {
        ElMessage.error(res.msg);
      }
    });
};

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  console.log(row);
  
  data.FormVisible = true;
};

const delUser = () => {
  request.delete("/productAPI/product/" + data.productId).then((res) => {
    if (res.code === 1) {
      load(); //重新加载数据
      data.centerDialogVisible = false;
      ElMessage.success("商品删除成功");
    } else {
      ElMessage.error(res.msg);
      data.centerDialogVisible = false;
    }
  });
};

const del = (id) => {
  data.centerDialogVisible = true;
  data.productId = id;
};

const outputExcel = () => {
  location.href = "http://localhost:8080/download/user";
};

const uploadFile = (item) => {
  //上传文件的需要formdata类型;所以要转
  let FormDatas = new FormData();
  FormDatas.append("file", item.file);
  request
    .request({
      url: "upload/user",
      method: "post",
      data: FormDatas,
      headers: data.headers,
    })
    .then((res) => {
      if (res.code === 1) {
        load(); //重新加载数据
        ElMessage.success("文件上传成功");
      } else {
        ElMessage.error(res.msg);
      }
    });
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.dialog {
  height: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>